<template>
  <appManageView
    :isLoading="isLoading"
    :data="formatData"
    :total="total"
    :pageSize="pageSize"
    :formLabelAlign="formLabelAlign"
    :currentPage="currentPage"
    :typeList="typeList"
    :grantTypeList="grantTypeList"
    :addAppdialog="addAppdialog"
    :editAppdialog="editAppdialog"
    @changePage="changePage"
    @sizeChange="sizeChange"
    @addClose="addClose"
    @addApp="addApp"
    @addCancel="addCancel"
    @addKeep="addKeep"
    @editClose="editClose"
    @editApp="editApp"
    @editCancel="editCancel"
    @editKeep="editKeep"
    @appDel="appDel"
    @findApp="findApp"
    @handleAvatarSuccess="handleAvatarSuccess"
    ref="appManage"
  ></appManageView>
</template>

<script>
  import appManageView from './appManageView';
  import {localUitl} from '@/utils/localUitl';

  export default {

    components: {
      appManageView
      // name
    },
    name: "appManageLogic",
    props: {
      // msg: String //  [name: typeof]
    },
    filters: {},
    computed: {},
    watch: {},
    data() {
      return {
        isLoading: false,
        data: [], // 树数据
        total: 0,  // 总条数
        pageSize: 10, // 每页条数
        formatData: [], // 当前页的数据
        formLabelAlign: { // form表单内容
          appName: '',
          clientID: '',
          clientSecred: '',
          redirectUris: '',
          serviceName: '',
          // brief: '',
          type: '',
          buildType: '',
          grantType: [],
          imageUrl: ''
        },
        currentPage: 1, // 当前页
        typeList: [], // 应用类型
        grantTypeList: [], // 授权类型
        addAppdialog: false, // 添加弹窗的状态
        editAppdialog: false, // 编辑弹窗的状态

      }
    },
    created() {
      this.getAppList();
      this.getGrantTypeAndClientType();
    },
    mounted() {

    },
    methods: {
      // 获取应用列表
      getAppList(obj) {
        this.isLoading = true;
        _https.post.getAppList(obj).then(res => {
          if (res.data.code == 0) {
            let newContent = [...res.data.data];
            let stationMap = new Map();
            let stationList = this.grantTypeList;
            for (let i = 0; i < stationList.length; i++) {
              stationMap.set(stationList[i].datavalue, stationList[i].datacode);
            }
            let newArr = newContent.map((item) => {
              let newPosition = item.authorizedgranttypes || [];
              let grantTypeName = "";
              for (let i = 0; i < stationList.length; i++) {
                for (let j = 0; j < newPosition.length; j++) {
                  if (newPosition[j] == stationList[i].datavalue) {
                    grantTypeName += "," + stationMap.get(stationList[i].datavalue);
                  }
                  item.grantTypeName = grantTypeName.substring(1);
                }
              }
              return item;
            });

            this.data = newArr;

            let currentPage = this.currentPage;
            if (res.data.data.length % this.pageSize == 0 && currentPage != 1) {
              currentPage = Math.ceil(res.data.data.length / this.pageSize);
              this.currentPage = currentPage;
            }
            this.setDataList(currentPage);
            this.total = res.data.data.length;
            this.isLoading = false;
          }
        })
      },
      // 获取授权类型列表和应用类型列表
      getGrantTypeAndClientType() {
        let grantTypeObj = {
          datatype: "grant_type"
        };
        _https.post.getDict(grantTypeObj).then(res => {
          if (res.data.code == 0) {
            this.grantTypeList = res.data.data;
          }
        });

        let clientTypeObj = {
          datatype: "client_type"
        };
        _https.post.getDict(clientTypeObj).then(res => {
          if (res.data.code == 0) {
            this.typeList = res.data.data;
          }
        })

      },
      /**
       * 将返回的数据进行分页操作
       * @param currentPage {Number}
       */
      setDataList(currentPage) {
        let current = currentPage * this.pageSize;
        let currentStart = current - this.pageSize;
        let currentEnd = current;
        this.formatData = this.data.slice(currentStart, currentEnd);
      },
      /**
       * 分页改变当前页触发
       * @param page 返回值参数（当前页）
       */
      changePage(page) {
        this.currentPage = page;
        this.setDataList(page);
        this.reset();
      },
      /**
       * 改变每页条数的回调
       * @param num 每页条数
       */
      sizeChange(num) {
        this.pageSize = num;
        this.getAppList();
      },
      // add弹窗关闭的回调
      addClose() {
        this.addAppdialog = false;
        this.$refs.appManage.$refs.addAppform.resetFields();
        this.reset();
      },
      // 新增应用
      addApp() {
        this.addAppdialog = true;
      },
      // 取消新增应用
      addCancel() {
        this.addAppdialog = false;
      },
      // 保存新增应用
      addKeep() {
        this.$refs.appManage.$refs.addAppform.validate((valid) => {
          if (!valid) {
            return;
          } else {
            let formLabelAlign = this.formLabelAlign;
            let newObj = {
              name: formLabelAlign.appName,
              secret: "",
              appid: "",
              authorizedgranttypes: formLabelAlign.grantType.join(","),
              scope: "app",
              registeredredirecturis: formLabelAlign.redirectUris,
              servicename: formLabelAlign.serviceName,
              buildType: formLabelAlign.buildType,
              type: formLabelAlign.type,
              icon: formLabelAlign.imageUrl,
              // code: "",
              // id: "",
              // brief: formLabelAlign.brief,
            };

            _https.post.getSaveClient(newObj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.getAppList();
                this.addAppdialog = false;
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 关闭编辑应用弹窗的回调
      editClose() {
        this.editAppdialog = false;
        this.$refs.appManage.$refs.editAppform.resetFields();
        this.reset();
      },
      // 编辑应用
      editApp(index, row) {
        this.formLabelAlign = {
          appName: row.name,
          clientID: row.id,
          clientSecred: row.secret,
          redirectUris: row.registeredredirecturis,
          servicename: '',
          // brief: '',
          buildType: row.buildType,
          type: row.type,
          grantType: row.authorizedgranttypes,
          imageUrl: row.icon
        };
        this.editAppdialog = true;
      },
      // 取消编辑应用
      editCancel() {
        this.editAppdialog = false;
      },
      // 保存编辑应用
      editKeep() {
        this.$refs.appManage.$refs.editAppform.validate((valid) => {
          if (!valid) {
            return;
          } else {
            let formLabelAlign = this.formLabelAlign;
            let newObj = {
              id: formLabelAlign.clientID,
              name: formLabelAlign.appName,
              secret: formLabelAlign.clientSecred,
              appid: formLabelAlign.clientID,
              authorizedgranttypes: formLabelAlign.grantType.join(","),
              scope: "app",
              registeredredirecturis: formLabelAlign.redirectUris,
              servicename: formLabelAlign.serviceName,
              buildType: formLabelAlign.buildType,
              type: formLabelAlign.type,
              icon: formLabelAlign.imageUrl,
              // code: "",
              // brief: formLabelAlign.brief,
            };

            _https.post.getUpdateClient(newObj).then(res => {
              if (res.data.code == 0) {
                this.$message({type: 'success', message: res.data.message});
                this.getAppList();
                this.editAppdialog = false;
              } else {
                this.$message({type: 'error', message: res.data.message});
              }
            })
          }
        })
      },
      // 删除编辑应用
      appDel(index, row) {
        let newObj = {
          id: row.id
        };
        this.$confirm('此操作将永久删除该应用, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _https.post.getDeleteClient(newObj).then(res => {
            if (res.data.code == 0) {
              this.$message({type: 'success', message: res.data.message});
              this.getAppList();
            } else {
              this.$message({type: 'error', message: res.data.message});
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 查询
      findApp(appSeach) {
        this.currentPage = 1;
        let obj = {
          name: appSeach
        };
        this.getAppList(obj);
      },
      handleAvatarSuccess(res) {
        this.formLabelAlign.imageUrl = res.data[0].httppath;
      },
      // 初始化
      reset() {
        this.formLabelAlign = {
          clientID: '',
          clientSecred: '',
          // brief: '',
          grantType: [],
          imageUrl: ''
        }
      }
    }
    ,
    destroyed() {

    }
  }
</script>

<style scoped lang="less">

</style>
